package com.yxjme.egcviewlibrary.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.CornerPathEffect;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.Path;
import android.graphics.PathEffect;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import java.util.ArrayList;

public class ECGView1 extends View {

    //网格间距
    private float gap_grid;
    //本页面宽，高
    private int width,height;
    //原点x坐标
    private int xori;
    //横、纵线条数
    private int grid_hori,grid_ver;
    //两点间横坐标间距
    private float gap_x = 10 ;
    //每小格内的数据个数
    private int dataNum_per_grid = 18;
    //中心y值
    private float y_center;

    private ArrayList<String> data_source;

    private float x_change ;//滑动查看时，x坐标的变化
    private static float x_changed ;
    private static float startX;//手指touch屏幕时候的x坐标
    private int data_num;//总的数据个数
    private float offset_x_max;//x轴最大偏移量



    /**绘制path的颜色*/
    private int pathColor = Color.RED ;
    private int pathStorkWidth = 5 ;


    public void setPathColor(int pathColor) {
        this.pathColor = pathColor;
    }

    public void setPathStorkWidth(int pathStorkWidth) {
        this.pathStorkWidth = pathStorkWidth;
    }

    public ECGView1(Context context, AttributeSet attrs){
        super(context,attrs);
        //背景色
//        this.setBackgroundColor(getResources().getColor(R.color.black));
    }


    public ECGView1(Context context){
        super(context);
        //背景色
//        this.setBackgroundColor(getResources().getColor(R.color.w));
    }





    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(MeasureSpecWidth(widthMeasureSpec),MeasureSpecHeight(heightMeasureSpec));
    }

    /**
     * 测量view 高度
     * @param heightMeasureSpec
     * @return
     */
    private int MeasureSpecHeight(int heightMeasureSpec) {
        final int minimumHeight = getSuggestedMinimumHeight();
        int h = 0 ;
        int heightMode = View.MeasureSpec.getMode(heightMeasureSpec);
        int height = View.MeasureSpec.getSize(heightMeasureSpec);
        if (heightMode == View.MeasureSpec.EXACTLY){
            /*固定值*/
            h =  height ;
        }else {
            if (heightMode == View.MeasureSpec.AT_MOST){
                h =  getPaddingBottom() + getPaddingTop() + 200;
            }else {
                h = Math.max(minimumHeight, height);
            }
        }
        return h;
    }

    /**
     * 测量view的宽度
     *
     * @param widthMeasureSpec
     * @return
     */
    private int MeasureSpecWidth(int widthMeasureSpec) {
        final int minimumWeight =getSuggestedMinimumWidth ();
        int widthMode = View.MeasureSpec.getMode(widthMeasureSpec);
        int width = View.MeasureSpec.getSize(widthMeasureSpec);
        int w = 0 ;
        if (widthMode == View.MeasureSpec.EXACTLY){
            /*固定值*/
            w =  width ;
        }else {
            if (widthMode == View.MeasureSpec.AT_MOST){
                w =  getPaddingBottom() + getPaddingTop() + 200;
            }else {
                w = Math.max(minimumWeight, width);
            }
        }
        return w ;
    }


    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        if (changed){

            xori = 0;
            /*线与线之间的间隔距离*/
            gap_grid = 30.0f;

            width = getWidth();
            height = getHeight();

            /*横线的总数*/
            grid_hori = height/(int)gap_grid;
            /*竖线的条数*/
            grid_ver = width/(int)gap_grid;
            /*中心线的 y坐标*/
            y_center = height/2;

//            data_num = data_source.size();
//            x_change = 0.0f ;
//            x_changed = 0.0f ;
//            offset_x_max = width - gap_x * data_num;
//            rect_gap_x = (float) width/data_num;
//            rect_width = (float) width * width/(gap_x * data_num);
//            multiple_for_rect_width = (float) width/rect_width;
            Log.e("json","本页面宽： " + width +"  高:" + height);
        }
        super.onLayout(changed, left, top, right, bottom);
    }



    public void maxOffsetX(){
        data_num = data_source.size();
        x_change = 0.0f ;
        x_changed = 0.0f ;
        offset_x_max = width - gap_x * data_num;


        switch (mode){
            case LEFT_TO_RIGHT:
                x_changed = offset_x_max;
                break;
            case RIGHT_TO_LEFT:
                if (offset_x_max<=0){
                    x_changed = offset_x_max;
                }
                break;
        }
    }


    ECGView.MODE mode = ECGView.MODE.RIGHT_TO_LEFT;


    /**
     * 执行的方向
     * @param mode
     */
    public void setMode(ECGView.MODE mode) {
        this.mode = mode;
    }



    public enum MODE{
        LEFT_TO_RIGHT,RIGHT_TO_LEFT
    }



    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));
        DrawGrid(canvas);
        DrawECGWave(canvas);
    }

    /**默认支持绘制网格*/
    private boolean isSupportGrid = true;
    /**默认支持绘制竖线*/
    private boolean isSupportGrid_ver = true;
    /**默认支持绘制横线*/
    private boolean isSupportGrid_hor = true ;
    /**是否需要支持实线*/
    private boolean isSupportShiXian = true;
    /**虚线点的宽和点点间隔*/
    private int lineWidth = 1;
    private int lineStorkWidth = 2;
    private int lineSpeed = 5;
    /**设置虚线的颜色*/
    private int lineColor = Color.RED;
    /**是否支持滑动*/
    private boolean isSupportScroll = true;


    private int gap_x_count ;
    public void setGap_x_count(int gap_x_count ) {
        this.gap_x_count = gap_x_count;
    }


    /**
     * 设置两点之间距离
     *
     * @param gap_x
     */
    public void setGap_x(float gap_x) {
        this.gap_x = gap_x;
    }


    /**
     * @param supportScroll
     */
    public void setSupportScroll(boolean supportScroll) {
        isSupportScroll = supportScroll;
    }

    public boolean isSupportScroll() {
        return isSupportScroll;
    }

    /**
     * @param lineColor
     */
    public ECGView1 setLineColor(int lineColor) {
        this.lineColor = lineColor;
        return ECGView1.this ;
    }


    public ECGView1 setLineStorkWidth(int lineStorkWidth) {
        this.lineStorkWidth = lineStorkWidth;
        return ECGView1.this ;
    }


    public ECGView1 setLineWidth(int lineWidth) {
        this.lineWidth = lineWidth;
        return ECGView1.this;
    }

    public ECGView1 setLineSpeed(int lineSpeed) {
        this.lineSpeed = lineSpeed;
        return ECGView1.this ;
    }


    /**
     * 是否支持每个五条之后绘制实线
     * @param b
     * @return
     */
    public ECGView1 isSupportShiXian(boolean b) {
        this.isSupportShiXian = b ;
        return ECGView1.this;
    }

    /**
     * 是否支持 绘制网格
     *
     * @param b
     * @return
     */
    public ECGView1 isSupportGrid(boolean b){
        this.isSupportGrid=b ;
        return ECGView1.this ;
    }

    /**
     * 是否支持绘制竖线
     *
     * @param b
     * @return
     */
    public ECGView1 isSupportGrid_ver(boolean b) {
        this.isSupportGrid_ver=b;
        return ECGView1.this;
    }


    /**
     * 是否支持绘制横线
     * @param b
     * @return
     */
    public ECGView1 isSupportGrid_hor(boolean b) {
        this.isSupportGrid_hor = b ;
        return ECGView1.this;
    }



    /**
     * 画背景网格
     */
    private void DrawGrid(Canvas canvas){

        /*是否支持绘制网格*/
        if (isSupportGrid){


            if (isSupportGrid_hor){
                //横线
                for (int i = 1 ; i < grid_hori + 2 ; i ++){
                    Paint paint = new Paint();
                    paint.setStyle(Paint.Style.STROKE);
                    paint.setColor(lineColor); //<color name="data_pr">#0a7b14</color>
                    paint.setStrokeWidth(lineStorkWidth);
                    Path path = new Path();
                    path.moveTo(xori, gap_grid * (i-1) + (height-grid_hori*gap_grid)/2);
                    path.lineTo(width,gap_grid * (i-1) + (height-grid_hori*gap_grid)/2);


                    if (isSupportShiXian){
                        if ( i % 5 != 0 ){//每第五条，为实线   其余为虚线 ，以下为画虚线方法
                            /*参数解释  float[] 第一个参数表示虚线长度 ，第二个参数表示虚线点间隔距离*/
                            PathEffect effect = new DashPathEffect(new float[]{lineWidth,lineSpeed},1);
                            paint.setPathEffect(effect);
                        }
                    }else {
                        PathEffect effect = new DashPathEffect(new float[]{lineWidth,lineSpeed},1);
                        paint.setPathEffect(effect);
                    }


                    canvas.drawPath(path,paint);
                }
            }



            if (isSupportGrid_ver){
                //竖线
                for (int i = 1 ; i < grid_ver + 2 ; i ++){
                    Paint paint = new Paint();
                    paint.setStyle(Paint.Style.STROKE);
                    paint.setColor(lineColor);
                    paint.setStrokeWidth(lineStorkWidth);
                    Path path = new Path();
                    path.moveTo(gap_grid * (i-1) + (width-grid_ver*gap_grid)/2, 0);
                    path.lineTo(gap_grid * (i-1) + (width-grid_ver*gap_grid)/2,height);

                    if (isSupportShiXian){
                        if (i % 5 != 0 ){
                            PathEffect effect = new DashPathEffect(new float[]{lineWidth,lineSpeed},1);
                            paint.setPathEffect(effect);
                        }
                    }else {
                        PathEffect effect = new DashPathEffect(new float[]{lineWidth,lineSpeed},1);
                        paint.setPathEffect(effect);
                    }
                    canvas.drawPath(path,paint);
                }
            }
        }
    }



    /**
     * 画心电图
     */
    private void DrawECGWave(Canvas canvas){
        this.canvas = canvas;
        if (data_source==null)return;

        if (gap_x_count!=0){
            gap_x = (float) (width * 1.0 /gap_x_count);
        }

        Paint paint = new Paint();
        paint.setStrokeJoin(Paint.Join.ROUND);
        paint.setStrokeCap(Paint.Cap.ROUND);
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(pathColor);
        paint.setStrokeWidth(pathStorkWidth);
        CornerPathEffect cornerPathEffect = new CornerPathEffect(200);
        paint.setPathEffect(cornerPathEffect);

        Path path = new Path();
        x_changed += x_change;
        if (x_changed > xori){
            //防止向右滑动太多 超左边界
            x_changed = xori;
        }else if (x_changed < offset_x_max ){
            //防止向左滑动太多 超右边界
            x_changed = offset_x_max;
        }
        switch (mode){
            case LEFT_TO_RIGHT:
                LeftToRight(path);
                break;
            case RIGHT_TO_LEFT:
                RightToLeft(path);
                break;
        }
        canvas.drawPath(path,paint);
    }



    private void LeftToRight(Path path) {
        path.moveTo(0, y_center);
        for (int i = 1; i < this.data_source.size(); i ++){
            float nnn = xori + gap_x * i +  x_changed;
            if (nnn < width + gap_x){
                float y = y_center;
                if(i%2==0){
                    y= (int) getY_coordinate(data_source.get(i));
                }
                path.lineTo(xori + gap_x * i  ,y);
            }
        }
        path.lineTo(xori + gap_x *  data_source.size()+1 , y_center);
        path.lineTo(width , y_center);
    }



    /**
     * @param path
     */
    private void RightToLeft(Path path) {
        path.moveTo(0, y_center);
        //此处 xori设置为0 ，未用上
        int iXor = 1;
        for (int i = 1 ; i < this.data_source.size() ; i ++){
            float nnn = xori + gap_x * i+x_changed;
            if (nnn >= 0 ){
                iXor = i;
                path.lineTo(nnn, y_center);
                break;
            }
        }
        for (int i = iXor; i < this.data_source.size(); i ++){
            float nnn = xori + gap_x * i +  x_changed;
            if (nnn < width + gap_x){
                path.lineTo(xori + gap_x * i +x_changed , getY_coordinate(data_source.get(i)));
            }
        }

        path.lineTo(xori + gap_x * data_source.size() +x_changed , y_center);
        if (gap_x * data_source.size()<width){
            path.lineTo(width , y_center);
            Log.v("======sd=====","sd");
        }
    }




    /**
     * 滑动查看心电图
     * @param event
     * @return
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!isSupportScroll&&offset_x_max>0){
            return false;
        }else {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    startX=event.getX();
                    break;
                case MotionEvent.ACTION_MOVE:
                    x_change = event.getX()-startX;
                    invalidate();
                    break;
            }
            return true;
        }
    }




    /**
     * 将数值转换为y坐标，中间大的显示心电图的区域
     */
    private float getY_coordinate(String data){
        int y_int = Integer.parseInt(data);
        y_int = (y_int - 2048) *(-1);
        float y_coor = 0.0f;
        y_coor = y_int *1/2 + y_center;
        return y_coor;
    }


    /**
     * 暴露接口，设置数据源
     */
    public void setData(ArrayList<String> data){
        this.data_source = data;
        maxOffsetX();
        invalidate();
    }



    private Canvas canvas ;




    /*重置*/
    public void clear() {
        if (canvas !=null){
            Paint paint = new Paint();
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
            canvas.drawPaint(paint);
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
            data_source = null;
            canvas = null ;
            invalidate();
        }
    }
}
